package com.memoryangelapplication;

/*
 * Process Events At the Registration and List Events From The Database*/
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.memoryangelapplication.constant.MemoryAngelConstant;
import com.memoryangelapplication.deviceinfo.MemoryAngelDeviceInfo;
import com.memoryangelapplication.notification.MemoryAngel_Subscription;
import com.memoryangelapplication.services.EventAlarm;
import com.memoryangelapplication.services.JSONfunctions;
import com.memoryangelapplication.services.PendingEventAlarm;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.AudioManager;
import android.os.AsyncTask;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class MemoryAngelEventsList extends Activity {
	ProgressDialog mProgressDialog;
	// Database Name
	private static final String DATABASE_NAME = "memoryangel.db";
	private static final String TAG = null;
	// Master Tables
	private String MEM_USER = "table_user";
	private String MEM_EVENT = "table_events";
	private String MEM_DEVICE = "table_device";
	private SQLiteDatabase mydb;
	String eventPreTime, DayhourValstr, DayhourValstrl, TagId;
	String deviceOpID;
	int devicestatus = 1;
	Intent service_intent;
	String IMEINumber, BateryLevel;
	int SIMState, Network = 0;
	String longitude = "0", latitude = "0";
	ArrayList<HashMap<String, String>> arraylist;
	ArrayList<HashMap<String, String>> arraylistevent;
	InputStream is = null;
	StringBuilder sb = null;
	int timeoutConnection = 5000;
	HttpParams httpParameters = new BasicHttpParams();
	String result;
	String mainUrl = null;
	String RegisterEventsUrl = null;
	JSONArray jArray;
	double[] loc = new double[2];
	JSONObject jsonobject;
	JSONObject jsonobjectevent;
	JSONArray jsonarray;
	String callState;
	TextView opname_text;
	Button ok_btn_events;
	String CareerPhone = "0";
	long pasteventsLastTimeStamp = 0;
	String eventsalarmtimeschedule;
	String user_email, user_pass;
	int loginState;
	String DateSend, Time, Tzone;
	long TimeStampValue;
	String currentVolume;
	CountDownTimer timer;
	int ActCheck = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//Remove title bar
	    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
	    //Remove notification bar
	    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.memory_angel_events);

		opname_text = (TextView) findViewById(R.id.opname_text);
		// ok_btn_events = (Button) findViewById(R.id.ok_btn_events_activity);

		Bundle bundle = getIntent().getExtras();
		deviceOpID = bundle.getString("mem_angel_opID");
		callState = bundle.getString("mem_state_ID");

		// Time Zone Of the Current Phone
		Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"),
				Locale.getDefault());
		Date currentLocalTime = calendar.getTime();
		DateFormat date = new SimpleDateFormat("Z");
		Tzone = date.format(currentLocalTime);
		Tzone = " " + Tzone;

		checkUserSubscription();
		displayHeader();

		// saveDeviceInfo();
		mainUrl = MemoryAngelConstant.MA_REGISTER;
		RegisterEventsUrl = MemoryAngelConstant.MA_SYNC_REG_EVENTS;
		if (callState.equals("REGISTERED")) {
			listCurrentEvents();
		} else if (callState.equals("NEW")) {
			new newDeviceConfiguration().execute();
		}

		timer = new CountDownTimer(20000, 1000) {

			@Override
			public void onTick(long millisUntilFinished) {

				// Some work
			}

			@Override
			public void onFinish() {
				listCurrentEvents();
				timer.start(); // start it again after it finishes
				// Log.e("REQUEST :", "count restart");
			}
		}.start();
		;

	}

	private void checkUserSubscription() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		Cursor device_user = null;
		try {
			String query = "SELECT * FROM table_user";
			device_user = mydb.rawQuery(query, null);
		} catch (Exception e) {
		}

		if (device_user != null) {
			if (device_user.getCount() > 0) {
				while (device_user.moveToNext()) {
					user_email = device_user.getString(2);
					user_pass = device_user.getString(8);
					new UserValidation().execute();
				}
			}
		}
	}

	private class UserValidation extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(MemoryAngelEventsList.this);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDialog.setCancelable(false);
			// Set progressdialog title
			mProgressDialog.setTitle("Process Events");
			// Set progressdialog message
			mProgressDialog.setMessage("Processing User Events....");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub

			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(
						"http://memoryangel.com/wakandroiddemo/wakandroid/loginRequest.php");
				JSONObject json = new JSONObject();
				json.put("record1", user_email);
				json.put("record2", user_pass);
				JSONArray postjson = new JSONArray();
				postjson.put(json);
				// Log.e("REQUEST :", "requestUSER-PASS :" + postjson);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					if (result != null) {
						// Log.e("REQUEST :", "Login Result :" + result);
						jArray = new JSONArray(result);
						JSONObject json_data = null;
						for (int i = 0; i < jArray.length(); i++) {
							json_data = jArray.getJSONObject(i);
							String login_state = json_data
									.getString("login_state");
							if (login_state.equals("success")) {
								loginState = 1;
							} else if (login_state.equals("false")) {
								loginState = 2;
							} else if (login_state.equals("expaired")) {
								loginState = 3;
							}
						}
					}

				}

			} catch (Exception e) {

			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			mProgressDialog.dismiss();
			if (loginState == 3) {
				Intent intentSubcription = new Intent(getBaseContext(),
						MemoryAngel_Subscription.class);
				intentSubcription.putExtra("TAGIDEMAIL", user_email);
				startActivity(intentSubcription);
			} else {
				listCurrentEvents();
			}
		}
	}

	public void onDestroy() {
		super.onDestroy();
	}

	public void onClick(View v) {

		switch (v.getId()) {

		case R.id.ok_btn_events_activity:
			checkpreevents();
			mProgressDialog.cancel();
			Bundle bundle = new Bundle();
			EventAlarm alarm1 = new EventAlarm(this, bundle, 1);
			break;

		}
	}

	private void checkpreevents() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		Cursor allrowitemsdes = null;
		int gmtOffset = TimeZone.getDefault().getRawOffset();
		long nowunixtime = (System.currentTimeMillis() + gmtOffset) / 1000;
		try {
			String query = "SELECT * FROM table_events WHERE event_active !='3' AND event_alam_time < '"
					+ nowunixtime + "' ORDER BY event_alam_time ASC";
			allrowitemsdes = mydb.rawQuery(query, null);
		} catch (Exception e) {
		}
		if (allrowitemsdes != null) {
			if (allrowitemsdes.getCount() > 0) {
				while (allrowitemsdes.moveToNext()) {
					String updateID = allrowitemsdes.getString(1);
					String eventReminderNumber = allrowitemsdes.getString(17);
					String event_ack_count = allrowitemsdes.getString(15);
					String event_status = allrowitemsdes.getString(5);
					if (event_status.equals("5")) {
						// SEND SMS
					}

					/*
					 * Bundle bundle = new Bundle(); EventAlarm alarm1 = new
					 * EventAlarm(this, bundle, 1);
					 */
				}

			} else {
				finish();
				return;
			}
		} else {
			finish();
			return;
		}
		finish();
		allrowitemsdes.close();
		mydb.close();

	}

	private void displayHeader() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		Cursor cur_opuser = null;

		try {
			cur_opuser = mydb.query(MEM_USER, null, null, null, null, null,
					null);
		} catch (Exception e1) {
		}
		if (cur_opuser != null) {
			if (cur_opuser.getCount() > 0) {
				while (cur_opuser.moveToNext()) {
					String op_user = cur_opuser.getString(6);
					CareerPhone = cur_opuser.getString(4);
					Log.e("REQUEST :", "CareerPhone :" + CareerPhone);
					opname_text.setText(op_user);
				}
			}
		}
		cur_opuser.close();
		mydb.close();
	}

	// DownloadJSON AsyncTask
	private class newDeviceConfiguration extends AsyncTask<Void, Void, Void> {

		private final String TAG = null;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(MemoryAngelEventsList.this);
			// Set progressdialog title
			mProgressDialog.setTitle("Process Device");
			// Set progressdialog message
			mProgressDialog.setMessage("Process Device Registration...");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// Create the array
			mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE,
					null);
			Cursor allrawdevice = null;
			try {
				String query = "SELECT * FROM table_device ORDER BY device_id DESC";
				allrawdevice = mydb.rawQuery(query, null);
			} catch (Exception e) {
			}
			if (allrawdevice != null) {
				if (allrawdevice.getCount() > 0) {
					while (allrawdevice.moveToNext()) {
						String updateID = allrawdevice.getString(0);
						IMEINumber = allrawdevice.getString(1);
						longitude = allrawdevice.getString(2);
						latitude = allrawdevice.getString(3);
						currentVolume = allrawdevice.getString(4);
						BateryLevel = allrawdevice.getString(5);
						String device_update_time = allrawdevice.getString(6);

					}
				}
			}

			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(mainUrl);
				JSONObject json = new JSONObject();

				json.put("record1", IMEINumber);
				json.put("record2", deviceOpID);
				json.put("record3", Network);
				json.put("record4", "0");
				json.put("record5", latitude);
				json.put("record6", longitude);
				json.put("record7", BateryLevel);
				json.put("record8", currentVolume);

				JSONArray postjson = new JSONArray();
				postjson.put(json);
				// Log.e("REQUEST :", "request :" + postjson);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					if (result != null) {
						arraylist = new ArrayList<HashMap<String, String>>();
						jsonobject = new JSONObject(result);
						try {
							// Locate the array name
							jsonarray = jsonobject.getJSONArray("posts");
						
							for (int i = 0; i < jsonarray.length(); i++) {
								HashMap<String, String> map = new HashMap<String, String>();
								jsonobject = jsonarray.getJSONObject(i);

								// Save Register OP in to Database
								mydb = openOrCreateDatabase(DATABASE_NAME,
										Context.MODE_PRIVATE, null);
								ContentValues newrowfDealer = new ContentValues();
								String userEmail = jsonobject
										.getString("email");
								Cursor checkUser = null;
								
								try {
									String query = "SELECT * FROM table_user Where user_carer_email = '"
											+ userEmail + "'";
									checkUser = mydb.rawQuery(query, null);
								} catch (Exception e) {
								}

								if (checkUser != null) {
									if (checkUser.getCount() > 0) {
										while (checkUser.moveToNext()) {
											ContentValues updateUser = new ContentValues();
											String updateID = checkUser
													.getString(0);
											String phone = checkUser
													.getString(1);
											Log.e("ERROR :", "Registered User Update:" + phone);
											updateUser
													.put("user_carer_id",
															jsonobject
																	.getString("carerID"));
											updateUser
													.put("user_carer_email",
															jsonobject
																	.getString("email"));
											updateUser.put("user_carer_name",
													jsonobject
															.getString("name"));
											updateUser
													.put("user_carer_sms",
															jsonobject
																	.getString("carerSMS"));
											updateUser.put("user_op_id",
													jsonobject
															.getString("opID"));
											updateUser
													.put("user_op_name",
															jsonobject
																	.getString("opName"));
											updateUser.put("user_reg_date",
													getAddDateTimeString()
															.toString());
											updateUser
													.put("user_secreat",
															jsonobject
																	.getString("password"));

											mydb.update(MEM_USER, updateUser,
													"user_id ='" + updateID
															+ "'", null);
											String phoneno = jsonobject.getString("carerSMS");
											Log.e("ERROR :", "Registered User:" + phoneno);
										}
									} else {
										try {
											newrowfDealer
													.put("user_carer_id",
															jsonobject
																	.getString("carerID"));
											newrowfDealer
													.put("user_carer_email",
															jsonobject
																	.getString("email"));
											newrowfDealer.put(
													"user_carer_name",
													jsonobject
															.getString("name"));
											newrowfDealer
													.put("user_carer_sms",
															jsonobject
																	.getString("carerSMS"));
											newrowfDealer.put("user_op_id",
													jsonobject
															.getString("opID"));
											newrowfDealer
													.put("user_op_name",
															jsonobject
																	.getString("opName"));
											newrowfDealer.put("user_reg_date",
													getAddDateTimeString()
															.toString());
											newrowfDealer
													.put("user_secreat",
															jsonobject
																	.getString("password"));

											mydb.insert(MEM_USER, null,
													newrowfDealer);
										} catch (Exception e) {
											Log.e("ERROR :", "Register Fail");
										}
									}
								}
								mydb.close();
							}
						} catch (JSONException e) {
							Log.e("ERROR :", "Register Fail");
						}

					}
					// Log.e("RESPONCE :", "result :" + result);
				}

			} catch (Exception e) {

			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			// Locate the listview in listview_main.xml
			mProgressDialog.dismiss();
			new fetchingEvents().execute();
		}
	}

	// DownloadJSON AsyncTask
	private class fetchingEvents extends AsyncTask<Void, Void, Void> {

		private final String TAG = null;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(MemoryAngelEventsList.this);
			// Set progressdialog title
			mProgressDialog.setTitle("Processing");
			// Set progressdialog message
			mProgressDialog.setMessage("Processing Events...");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// Get Events Results
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				// RegisterEventsUrl
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(RegisterEventsUrl);
				JSONObject json = new JSONObject();
				json.put("record1", deviceOpID);
				JSONArray postjson = new JSONArray();
				postjson.put(json);
				Log.e("REQUEST :", "request events 333:" + postjson);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();

				if (is != null) {
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					Log.v(TAG, "Responce MEMLIST EVENTS:" + result);
					JSONObject jsonResponse = new JSONObject(result);
					JSONArray jsonArray = jsonResponse
							.getJSONArray("eventlist");
					for (int i = 0; i < jsonArray.length(); i++) {
						JSONObject jObject = (JSONObject) jsonArray.get(i);

						String CureventTimeID = jObject.getString("eventid");
						String dateString = jObject.getString("eventdate");
						DateSend = dateString;
						String dateTime = jObject.getString("eventtime");
						String[] CheckAMPM = dateTime.split(" ");
						String CheckHourMin = CheckAMPM[0];
						String CheckAMPMSTR = CheckAMPM[1];

						String[] CheckHourMinArr = CheckHourMin.split(":");
						String CheckHour = CheckHourMinArr[0];
						String CheckMin = CheckHourMinArr[1];

						if (CheckAMPMSTR.equals("PM")) {
							int CheckHourVal = Integer.parseInt(CheckHour);
							if (CheckHourVal != 12) {
								int CheckH = CheckHourVal + 12;
								CheckHour = Integer.toString(CheckH);
							} else {
								int CheckH = 12;
								CheckHour = Integer.toString(CheckH);
							}
						} else if (CheckAMPMSTR.equals("AM")
								&& CheckHour.equals("12")) {
							CheckHour = "00";
						}

						dateTime = CheckHour + "" + CheckMin + ""
								+ CheckAMPMSTR;
						Time = CheckHour + ":" + CheckMin;
						String CurrentTimeStamp = jObject
								.getString("eventtimestamp");
						String CurrentStatus = jObject.getString("status");

						dateString = dateString.replaceAll("-", "");
						dateTime = dateTime.replaceAll(":", "");
						String formatTimeStamp = dateString.trim() + ""
								+ CheckHour + "" + CheckMin;
						String formatTime = dateString.trim() + dateTime.trim();

						long formatTimeStampVal = Long
								.parseLong(formatTimeStamp);
						long formatTimeStampCurrent = Long
								.parseLong(getAddDateTimeStringPreCheck()
										.toString());
						getNativeTimeStamp(DateSend, Time, Tzone);

						/*
						 * if (formatTimeStampVal < formatTimeStampCurrent) {
						 * Log.v(TAG, "checking times XXXXXXXX:" +
						 * formatTimeStampVal); if (pasteventsLastTimeStamp ==
						 * 0) { pasteventsLastTimeStamp =
						 * formatTimeStampCurrent; formatTimeStampVal =
						 * pasteventsLastTimeStamp; } else { formatTimeStampVal
						 * = pasteventsLastTimeStamp + 1; }
						 * 
						 * }
						 */

						String TimeStampValueStr = String
								.valueOf(TimeStampValue);
						eventsalarmtimeschedule = String
								.valueOf(formatTimeStampVal);

						mydb = openOrCreateDatabase(DATABASE_NAME,
								Context.MODE_PRIVATE, null);
						Cursor checkPreEvents = null;
						try {
							String query = "SELECT event_log_id,event_alam_time,event_status FROM table_events Where event_log_id = '"
									+ CureventTimeID + "'";
							checkPreEvents = mydb.rawQuery(query, null);
						} catch (Exception e) {
						}

						if (checkPreEvents != null) {
							if (checkPreEvents.getCount() > 0) {
								while (checkPreEvents.moveToNext()) {
									String updateID = checkPreEvents
											.getString(0);
									String updateTimeStamp = checkPreEvents
											.getString(1);
									String event_status = checkPreEvents
											.getString(2);

									if (CurrentStatus.equals("6") || CurrentStatus.equals("0") || CurrentStatus.equals("1")) {
										int Status = 1;
										if(event_status.equals("3")){
											Log.e("ERROR :", "Already Acknoledge");
										}
										else{
										ContentValues updateEvets = new ContentValues();
										updateEvets.put("event_log_id",
												jObject.getString("eventid"));
										updateEvets.put("event_user_id",
												jObject.getString("opid"));
										updateEvets.put("event_title",
												jObject.getString("title"));
										updateEvets
												.put("event_description",
														jObject.getString("description"));
										updateEvets.put("event_status", Status);
										updateEvets.put("event_date",
												jObject.getString("eventdate"));
										updateEvets.put("event_time",
												jObject.getString("eventtime"));
										/*
										 * updateEvets .put("event_alam_time",
										 * jObject.getString("eventtimestamp"));
										 */
										updateEvets.put("event_alam_time",
												eventsalarmtimeschedule);

										updateEvets.put("event_active", "0");
										updateEvets.put("event_user_phoneno",
												CareerPhone);
										updateEvets.put("event_url",
												jObject.getString("url"));
										updateEvets.put("event_package",
												jObject.getString("package"));
										updateEvets.put("event_time_stamp",
												formatTime);
										updateEvets.put("event_update_time",
												getAddDateTimeString()
														.toString());
										updateEvets.put("event_ack_count", "0");

										updateEvets
												.put("eventReminderTime",
														jObject.getString("eventremindertime"));
										updateEvets
												.put("eventReminderNumber",
														jObject.getString("eventremindernumber"));
										updateEvets
												.put("eventWaitTime",
														jObject.getString("eventwaittime"));
										updateEvets
												.put("eventNotifyType",
														jObject.getString("eventmissednotification"));
										updateEvets.put("eventTimeStamp",
												TimeStampValueStr);

										// Log.e("ERROR :", "Update Event :"
										// + jObject.getString("eventid"));
										mydb.update(MEM_EVENT, updateEvets,
												"event_log_id ='" + updateID
														+ "'", null);
										}
									} else if (CurrentStatus.equals("7")) {
										if(event_status.equals("3")){
											Log.e("ERROR :", "Already Acknoledge");
										}
										else{
											Log.e("ERROR :", "Event Delete******");
											ContentValues updateEvets = new ContentValues();
											updateEvets.put("event_status", "7");
											updateEvets.put("event_active", "1");
											mydb.update(MEM_EVENT, updateEvets,
													"event_log_id ='" + updateID
															+ "'", null);
										}
									} else {
										Log.e("ERROR :", "Event Not Changed");
										
									}

								}
							} else {
								int Status = 1;
								/*
								 * String EventStatus
								 * =jObject.getString("event_notification_result"
								 * );
								 * 
								 * if(EventStatus.equals("NEW")){ Status = 1; }
								 * else if(EventStatus.equals("SCHEDULED")){
								 * Status = 1; } else
								 * if(EventStatus.equals("PROCESSED")){ Status =
								 * 2; } else
								 * if(EventStatus.equals("ACKNOWLEDGED")){
								 * Status = 3; } else
								 * if(EventStatus.equals("NOT ACKNOWLEDGED")){
								 * Status = 4; } else
								 * if(EventStatus.equals("TEXT NOTIFICATION SEND"
								 * )){ Status = 5; }
								 */
								ContentValues newregevent = new ContentValues();
								newregevent.put("event_log_id",
										jObject.getString("eventid"));
								newregevent.put("event_user_id",
										jObject.getString("opid"));
								newregevent.put("event_title",
										jObject.getString("title"));
								newregevent.put("event_description",
										jObject.getString("description"));
								newregevent.put("event_status", Status);
								newregevent.put("event_date",
										jObject.getString("eventdate"));
								newregevent.put("event_time",
										jObject.getString("eventtime"));
								/*
								 * newregevent .put("event_alam_time",
								 * jObject.getString("eventtimestamp"));
								 */
								newregevent.put("event_alam_time",
										eventsalarmtimeschedule);
								newregevent.put("event_active", "0");
								newregevent.put("event_user_phoneno",
										CareerPhone);
								newregevent.put("event_url",
										jObject.getString("url"));
								newregevent.put("event_package",
										jObject.getString("package"));
								newregevent.put("event_time_stamp", formatTime);
								newregevent.put("event_update_time",
										getAddDateTimeString().toString());
								newregevent.put("event_ack_count", "0");
								newregevent.put("eventReminderTime",
										jObject.getString("eventremindertime"));
								newregevent.put("eventReminderNumber", jObject
										.getString("eventremindernumber"));
								newregevent.put("eventWaitTime",
										jObject.getString("eventwaittime"));
								newregevent.put("eventNotifyType", jObject
										.getString("eventmissednotification"));
								newregevent.put("eventTimeStamp",
										TimeStampValueStr);

								Log.e("ERROR :",
										"Insert New :"
												+ jObject.getString("eventid"));
								mydb.insert(MEM_EVENT, null, newregevent);
							}
						}

						mydb.close();
					}

				}

			} catch (Exception e) {

			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			// Locate the listview in listview_main.xml
			mProgressDialog.dismiss();
			displayHeader();
			listCurrentEvents();

		}
	}

	private String getAddDateTimeString() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}

	public long getNativeTimeStamp(String DateSend, String Time, String Tzone) {
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm zzzzz");
		Calendar c = Calendar.getInstance();
		Date d = null;

		try {
			d = ddMMMyyFormat
					.parse(DateSend.trim() + " " + Time.trim() + Tzone);

		} catch (ParseException e) {
			e.printStackTrace();
		}

		c.setTime(d);

		String date_to_string = ddMMMyyFormat
				.format(c.getTimeInMillis() / 1000);
		TimeStampValue = c.getTimeInMillis() / 1000;
		return c.getTimeInMillis() / 1000;
	}

	private String getAddDateTimeStringPreCheck() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyyMMddHHmm");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}

	public void listCurrentEvents() {
		ActCheck = ActCheck + 1;
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.list_view_events_activity);
		String[] fromtrdes = new String[] { "item_result_1", "item_result_2",
				"item_result_3", "item_result_4" };
		int[] totrdes = new int[] { R.id.event_date, R.id.event_time,
				R.id.event_title, R.id.event_description };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		Cursor allrowitemsdes = null;

		try {
			String query = "SELECT event_title,event_description,event_date,event_time,event_status,event_time_stamp FROM table_events WHERE event_active ='0'  ORDER BY event_alam_time ASC";
			allrowitemsdes = mydb.rawQuery(query, null);
		} catch (Exception e) {
		}
		if (allrowitemsdes != null) {
			if (allrowitemsdes.getCount() > 0) {
				while (allrowitemsdes.moveToNext()) {
					String event_title = allrowitemsdes.getString(0);
					String event_description = allrowitemsdes.getString(1);
					String event_date = allrowitemsdes.getString(2);
					String event_time = allrowitemsdes.getString(3);

					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("item_result_1", event_date);
					maptrdes.put("item_result_2", event_time);
					maptrdes.put("item_result_3", event_title);
					maptrdes.put("item_result_4", event_description);
					fillMapstrdes.add(maptrdes);

					SimpleAdapter adaptertrdes = new SimpleAdapter(this,
							fillMapstrdes, R.layout.memory_angel_events_raw,
							fromtrdes, totrdes);
					lvtypedes.setAdapter(adaptertrdes);
				}
			}
		}
		mProgressDialog.cancel();
		allrowitemsdes.close();

		String nowunixtime = getAddDateTimeStringStamp().toString();
		Cursor checkPreviousAlerts = null;

		try {
			/*
			 * checkPreviousAlerts = mydb.query(MEM_EVENT, null,
			 * "event_active = '0' AND event_alam_time < '" + nowunixtime +
			 * "' AND event_ack_count = '0'", null, null, null, null);
			 */
			String query = "SELECT * FROM table_events Where event_active = '0' AND event_alam_time < '"
					+ nowunixtime
					+ "' AND event_ack_count = '0' ORDER BY event_log_id LIMIT 1";
			checkPreviousAlerts = mydb.rawQuery(query, null);
		} catch (Exception e) {
		}
		// Log.e("MEM LOG:", "EEE COUNT :"+checkPreviousAlerts.getCount());
		if (checkPreviousAlerts != null) {
			if (checkPreviousAlerts.getCount() > 0) {
				int count = 0;
				while (checkPreviousAlerts.moveToNext()) {
					Log.e("MEM LOG:", "Trigger Alarm From List*********:"
							+ checkPreviousAlerts.getCount());
				/*	Bundle bundle = new Bundle();
					EventAlarm alarm1 = new EventAlarm(getBaseContext(),
							bundle, 1);*/
				}
			}

		}
		checkPreviousAlerts.close();
		mydb.close();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			// new fetchingEvents().execute();
			// Do Code Here
			// If want to block just return false
			return false;
		}
		if (keyCode == KeyEvent.KEYCODE_MENU) {
			// new fetchingEvents().execute();
			// Do Code Here
			// If want to block just return false
			return false;
		}
		if (keyCode == KeyEvent.KEYCODE_HOME) {
			/*
			 * Bundle bundle = new Bundle(); PendingEventAlarm alarm1 = new
			 * PendingEventAlarm(getApplicationContext(), bundle, 1);
			 */
			// /////////
			new fetchingEvents().execute();
			Intent intent = new Intent(getBaseContext(),
					MemoryAngelLoading.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // You need this if
															// starting
															// the activity from
															// a service
			intent.setAction(Intent.ACTION_MAIN);
			intent.addCategory(Intent.CATEGORY_LAUNCHER);
			startActivity(intent);

			// Do Code Here
			// If want to block just return false
			return false;
		}
		if (keyCode == KeyEvent.KEYCODE_SEARCH) {

			// Do Code Here
			// If want to block just return false
			return false;
		}
		if (keyCode == KeyEvent.KEYCODE_SETTINGS) {

			// Do Code Here
			// If want to block just return false
			return false;
		}

		return super.onKeyDown(keyCode, event);
	}

	private String getAddDateTimeStringStamp() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyyMMddHHmm");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}

}
